# markdown_to_docx.py
import tkinter as tk
from tkinter import filedialog, messagebox
from docx import Document
import markdown
import os
import sys
from html.parser import HTMLParser

class MarkdownToDocxParser(HTMLParser):
    def __init__(self, document):
        super().__init__()
        self.doc = document
        self.current_paragraph = None
        self.current_list_style = None
        self.list_level = 0

    def handle_starttag(self, tag, attrs):
        if tag.startswith('h') and len(tag) == 2 and tag[1].isdigit():
            # 处理标题
            self.current_paragraph = 'heading'
            self.heading_level = int(tag[1])
        elif tag == 'p':
            # 处理段落
            self.current_paragraph = self.doc.add_paragraph()
        elif tag == 'strong' or tag == 'b':
            # 开始加粗文本
            self.current_run_style = 'bold'
        elif tag == 'em' or tag == 'i':
            # 开始斜体文本
            self.current_run_style = 'italic'
        elif tag == 'ul':
            # 开始无序列表
            self.current_list_style = 'List Bullet'
            self.list_level += 1
        elif tag == 'ol':
            # 开始有序列表
            self.current_list_style = 'List Number'
            self.list_level += 1
        elif tag == 'li':
            # 处理列表项
            if self.current_list_style:
                self.current_paragraph = self.doc.add_paragraph(style=self.current_list_style)
            else:
                self.current_paragraph = self.doc.add_paragraph()

    def handle_endtag(self, tag):
        if tag == 'p' or (tag.startswith('h') and len(tag) == 2 and tag[1].isdigit()):
            self.current_paragraph = None
        elif tag == 'ul' or tag == 'ol':
            self.list_level -= 1
            if self.list_level == 0:
                self.current_list_style = None
        elif tag == 'strong' or tag == 'b' or tag == 'em' or tag == 'i':
            self.current_run_style = None

    def handle_data(self, data):
        if self.current_paragraph:
            if self.current_paragraph == 'heading':
                # 添加标题
                self.doc.add_heading(data, level=min(self.heading_level, 9))
            else:
                # 添加段落文本
                run = self.current_paragraph.add_run(data)
                if hasattr(self, 'current_run_style'):
                    if self.current_run_style == 'bold':
                        run.bold = True
                    elif self.current_run_style == 'italic':
                        run.italic = True

def main():
    print("📝 请输入您的 Markdown 内容（输入 'q!' 然后回车结束输入）:")
    print("例如：")
    print("# 标题")
    print("这是**加粗**文本")
    print("- 列表项")
    print("q!")
    print("\n现在请输入您的内容：")

    # 读取多行输入
    lines = []
    try:
        while True:
            line = input()
            if line.strip() == 'q!':
                break
            lines.append(line)
    except KeyboardInterrupt:
        print("\n\n程序被用户中断")
        return
    except Exception as e:
        print(f"❌ 输入过程中发生错误: {e}")
        return

    md_content = "\n".join(lines)

    if not md_content.strip():
        print("❌ 输入为空，程序退出。")
        return

    # 将 Markdown 转为 HTML（docx 使用 HTML 结构）
    html_content = markdown.markdown(md_content)

    # 创建 Word 文档
    doc = Document()
    doc.add_heading("Markdown 转换文档", level=0)

    # 使用自定义解析器处理 HTML 内容
    parser = MarkdownToDocxParser(doc)
    parser.feed(html_content)

    # 使用 Tkinter 弹出保存对话框
    try:
        root = tk.Tk()
        root.withdraw()  # 隐藏主窗口
        root.attributes('-topmost', True)  # 确保对话框置顶显示
        save_path = filedialog.asksaveasfilename(
            title="💾 保存为 DOCX 文件",
            defaultextension=".docx",
            filetypes=[("Word 文档", "*.docx"), ("所有文件", "*.*")]
        )
        root.destroy()

        if not save_path:
            print("❌ 未选择保存位置，已取消。")
            return

        try:
            doc.save(save_path)
            # 只在支持GUI的环境下显示messagebox
            if sys.stdin.isatty() and sys.stdout.isatty():
                try:
                    messagebox.showinfo("✅ 成功", f"文档已保存为：\n{save_path}")
                except tk.TclError:
                    pass  # 忽略GUI相关错误
            print(f"\n🎉 转换完成！文件已保存：\n{os.path.abspath(save_path)}")
        except Exception as e:
            print(f"❌ 保存失败：{e}")
    except tk.TclError as e:
        print(f"⚠️ GUI 错误: {e}")
        print("请使用命令行方式指定输出文件名:")
        # 提供替代方案
        default_name = "markdown_output.docx"
        try:
            doc.save(default_name)
            print(f"📝 文档已保存为: {os.path.abspath(default_name)}")
        except Exception as save_error:
            print(f"❌ 保存失败: {save_error}")

if __name__ == "__main__":
    # 检查依赖
    try:
        import markdown
        from docx import Document
    except ImportError:
        print("🔧 请先安装依赖：")
        print("pip install markdown python-docx")
        exit(1)

    main()